//
//  AddAccountingViewModel.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 23.03.25.
//

import Foundation
class AddAccountingViewModel : KoiAccountingBaseViewModel {
    
    @Published var toastMsg = ""
    // 选中账本
    @Published var selectedBook: AccountingBook = BookManager.standard.currentBook()
    // 选中类别
    @Published var selectedCategory: AccountingCategory? = nil
    // 选中的子类别
    @Published var selectedSubCategory: AccountingCategory? = nil
    // 选中类别的子类别
    @Published var subCategoryList = Array<AccountingCategory>()
    // 选中详情(更新用)
    @Published var selectedDetail: AccountingDetail? = nil
    // 记账明细 id
    @Published var recordId = ""
    // 记账金额
    @Published var amount = "0.00"
    // 记账键盘公式重置
    @Published var reset = false
    // 记账日期
    @Published var selectedDate = Date()
    // 记账备注
    @Published var remark = ""
    // 支出类别集合
    @Published var expenseList = Array<AccountingCategory>()
    // 收入类别集合
    @Published var incomeList = Array<AccountingCategory>()
    // 用户的全部账本，用户切换账本
    @Published var books = Array<AccountingBook>()
    // 异步保存后监听状态
    @Published var saveState = ""
    // 二级类别是否处于展开状态
    @Published var isExpand = false
    // 记账明细数据访问层
    private let detailDao = KoiAccountingDB.standard.getDetailDao()
    // 类别数据访问层
    private let categoryDao = KoiAccountingDB.standard.getCategoryDao()
    // 账本数据访问层
    private let bookDao = KoiAccountingDB.standard.getBookDao()
    
    func saveRecord() {
        if (recordId.isEmpty) {
            createRecord()
        } else {
            updateRecord()
        }
    }
    
    private func createRecord() {
        let amountDouble = Double(amount)
        if (amountDouble == nil || amountDouble == 0.0) {
            toastMsg = "请输入金额"
            return
        }
        if (selectedCategory == nil) {
            toastMsg = "请选择类别"
            return
        }
        var selectCid = selectedCategory?.cid
        if (selectedSubCategory != nil) {
            selectCid = selectedSubCategory?.cid
        }
        let bookId = selectedBook.bookId
        
        let now = Date()
        let createTime = now.toISODateString()
        let detail = AccountingDetail(
            uid: uid,
            amount: amountDouble,
            date: selectedDate.toISODateString(),
            remark: remark,
            cid: selectCid,
            bookId: bookId,
            createTime: createTime,
            updateTime: createTime
        )
        asyncBackground {
            self.detailDao.saveRecord(accountingDetail: detail)
            self.asyncMain {
                self.saveState = "success"
            }
        }
        
    }
    
    private func updateRecord() {
        guard var detail = selectedDetail else { return }
        let amountDouble = Double(amount)
        if (amountDouble == nil || amountDouble == 0.0) {
            toastMsg = "请输入金额"
            return
        }
        if (selectedCategory == nil) {
            toastMsg = "请选择类别"
            return
        }
        var selectCid = selectedCategory?.cid
        if (selectedSubCategory != nil) {
            selectCid = selectedSubCategory?.cid
        }
        let needUpdate = detail.update(amount: amountDouble, date: selectedDate.toISODateString(), remark: remark, cid: selectCid, bookId: selectedBook.bookId)
        print("needUpdate")
        if !needUpdate {
            self.saveState = "success"
            return
        }
        asyncBackground {
            self.detailDao.updateRecord(detail: detail)
            self.asyncMain {
                self.saveState = "success"
            }
        }
    }
    
    func initDetail() {
        guard let detail = selectedDetail else { return }
        asyncBackground {
            let result = self.detailDao.getDetailRecord(recordId: detail.recordId, uid: self.uid, bookId: self.bookId)
            self.asyncMain {
                self.selectedDetail = result
            }
        }
    }
    
    func loadBooks() {
        DispatchQueue.global(qos: .background).async {
            var result = self.bookDao.getAllBook(uid: self.uid)
            DispatchQueue.main.async {
                result = self.getTestBook()
                self.books = result
            }
        }
    }
    
    func loadCategorys(selectedCategory: AccountingCategory? = nil) {
        let bookId = self.selectedBook.bookId ?? self.bookId
        DispatchQueue.global(qos: .background).async {
            // 一级类别，还是二级类别
            var firstCategory: AccountingCategory? = nil
            var subCategory: AccountingCategory? = nil
            var subCategoryList: [AccountingCategory] = [AccountingCategory]()
            if let category = selectedCategory {
                if category.isSubCategory() {
                    let parentId = category.parentId ?? ""
                    let parentCategory = self.categoryDao.getCategoryByCid(cid: parentId, uid: self.uid, bookId: bookId)
                    firstCategory = parentCategory
                    subCategory = category
                    subCategoryList = self.categoryDao.getSubCategoryListByParentId(uid: self.uid, bookId: bookId, parentId: parentId)
                } else {
                    firstCategory = selectedCategory
                }
            }
            let expenseResult = self.categoryDao.getCategoryByType(uid: self.uid, bookId: bookId, type: CategoryType.expense.rawValue)
            let incomeResult = self.categoryDao.getCategoryByType(uid: self.uid, bookId: bookId, type: CategoryType.income.rawValue)
            DispatchQueue.main.async {
                self.selectedCategory = firstCategory
                self.selectedSubCategory = subCategory
                print("firstCategory \(firstCategory?.name)")
                print("subCategory \(subCategory?.name)")
                self.expenseList = expenseResult
                self.incomeList = incomeResult
                self.subCategoryList = subCategoryList
                print("loadCategorys expenseList \(self.expenseList.count)")
                print("loadCategorys incomeList \(self.incomeList.count)")
            }
        }
    }
    
    func loadSubCategoryList(category: AccountingCategory?) {
        var bookId = self.selectedBook.bookId ?? self.bookId
        guard let category = category else { return }
        asyncBackground {
            let parentId = category.cid ?? ""
            let subCategoryList = self.categoryDao.getSubCategoryListByParentId(uid: self.uid, bookId: bookId, parentId: parentId)
            self.asyncMain {
                self.subCategoryList = subCategoryList
            }
        }
    }
    
    private func getTestBook() -> Array<AccountingBook> {
        return [
            AccountingBook(bookName: "默认账本"),
            AccountingBook(bookName: "工作账本"),
            AccountingBook(bookName: "生活账本"),
            AccountingBook(bookName: "旅行账本")
        ]
    }
}
